package id.co.rho.scoring.cid.shared.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: bungrudi
 * Date: 8/13/11
 * Time: 10:58 AM
 */
public class CollectionUtils {
    public static String append(Collection coll, String appender) {
        StringBuilder sb = new StringBuilder();
        for(Object o : coll) {
            if(sb.length() > 0) {
                sb.append(appender);
            }
            sb.append(o.toString());
        }
        return sb.toString();
    }
    public static <M> void forEach(Collection<M> coll, Closure<M> closure) {
        for(M t : coll) {
            closure.on(t);
        }
    }

    public static <M> List<M> select(Collection<M> col, Predicate<M> p) {
        ArrayList<M> result = new ArrayList<M>();
        for(M n : col) {
            if(p.select(n)) {
                result.add(n);
            }
        }
        return result;
    }

    public static <M,N> List<N> collect(Collection<M> col, Transformer<M,N> transformer) {
        ArrayList<N> result = new ArrayList<N>();
        for(M m : col) {
            result.add(transformer.transform(m));
        }
        return result;
    }
}
